package com.leantech.android.browser.dialog

import android.content.Context
import android.util.SparseIntArray
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.core.util.getOrDefault
import com.cscj.android.repository.db.entity.SearchEngineEntity
import com.cscj.android.repository.db.entity.UserAgentEntity
import com.cscj.android.repository.settings.model.SettingConstants
import com.jaygoo.widget.OnRangeChangedListener
import com.jaygoo.widget.RangeSeekBar
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.DialogImgBlockCenterBinding
import com.leantech.android.browser.databinding.LayoutBottomSheetCancelBinding
import com.leantech.android.browser.databinding.LayoutBottomSheetConfirmBinding
import com.leantech.android.browser.databinding.LayoutMenuFontSizeBinding
import com.leantech.android.browser.qmui.getBottomSheetListAdapter
import com.leantech.android.browser.utils.gone
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.visible
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.widget.dialog.QMUIBaseDialog
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheetListItemModel
import splitties.dimensions.dip
import splitties.resources.str
import splitties.resources.txt

object BottomSheetDialogHelper {

    const val TagCustomEngine = "CustomEngine"

    private val searchEngineIconMap = SparseIntArray().apply {
        put(1, R.drawable.icon_engine_baidu)
        put(2, R.drawable.icon_engine_360)
        put(3, R.drawable.icon_engine_wuzhui)
        put(4, R.drawable.icon_engine_bing)
        put(5, R.drawable.icon_engine_kuake)
        put(6, R.drawable.icon_engine_google)
    }

    fun getSearchEngineIcon(id: Int): Int {
        return searchEngineIconMap.getOrDefault(id, R.drawable.icon_search)
    }

    private fun createCancelFooterView(context: Context): LayoutBottomSheetCancelBinding {
        return LayoutBottomSheetCancelBinding.inflate(LayoutInflater.from(context))
    }

    private fun createConfirmFooterView(context: Context): LayoutBottomSheetConfirmBinding {
        return LayoutBottomSheetConfirmBinding.inflate(LayoutInflater.from(context))
    }

    fun createSearchEngineDialog(
        context: Context,
        searchEngines: List<SearchEngineEntity>,
        onItemClick: (SearchEngineEntity?) -> Unit,
        onDismiss: () -> Unit = {}
    ): QMUIBottomSheet {
        val checkedIndex = searchEngines.indexOfFirst { it.preferred }
        val cancelBinding = createCancelFooterView(context)
        val dialog = BottomListSheetBuilder(context, true).apply {
            setNeedRightMark(true)
            setCheckedIndex(checkedIndex)
            setSkinManager(QMUISkinManager.defaultInstance(context))
            setTitle(context.txt(R.string.text_search_engine))
            setAllowDrag(true)
            searchEngines.forEach { searchEngine ->
                val iconRes = searchEngineIconMap.getOrDefault(
                    searchEngine.id, R.drawable.icon_engine_default
                )
                addItem(iconRes, searchEngine.name, searchEngine.id.toString())
            }

            setFitNav(true)
            //暂时隐藏
//            addItem(R.drawable.icon_engine_default, "自定义搜索引擎", TagCustomEngine)

            addContentFooterView(cancelBinding.root)

            setOnSheetItemClickListener { dialog, _, position, _ ->
                onItemClick(searchEngines.getOrNull(position))
                dialog.dismiss()
            }
            setOnBottomDialogDismissListener {
                onDismiss()
            }

        }.build()

        cancelBinding.btnCancel.onThrottleClick {
            dialog.dismiss()
        }

        return dialog
    }

    fun createUASettingDialog(
        context: Context,
        items: List<UserAgentEntity>,
        onItemClick: (UserAgentEntity?) -> Unit,
        onDismiss: () -> Unit = {}
    ): QMUIBottomSheet {
        val checkedIndex = items.indexOfFirst { it.preferred }
        val cancelBinding = createCancelFooterView(context)
        val dialog = BottomListSheetBuilder(context, true).apply {
            setNeedRightMark(true)
            setSkinManager(QMUISkinManager.defaultInstance(context))
            setCheckedIndex(checkedIndex)
            setTitle(context.txt(R.string.text_ua_setting))
            setAllowDrag(true)
            items.forEach { agentEntity ->
                addItem(agentEntity.name, agentEntity.id.toString())
            }

            setFitNav(true)

            addContentFooterView(cancelBinding.root)


            setOnSheetItemClickListener { dialog, _, position, _ ->
                onItemClick(items.getOrNull(position))
                dialog.dismiss()
            }
            setOnBottomDialogDismissListener {
                onDismiss()
            }

        }.build()

        cancelBinding.btnCancel.onThrottleClick {
            dialog.dismiss()
        }

        return dialog
    }

    /**
     * 黑暗模式
     */
    fun createDarkModeDialog(
        context: Context, darkMode: Int, onDarkModeSelected: (QMUIBottomSheet, Int) -> Unit
    ): QMUIBottomSheet {

        val confirmBinding = createConfirmFooterView(context)
        val dialog = BottomListSheetBuilder(context, true).apply {
            setCheckedIndex(darkMode)
            setSkinManager(QMUISkinManager.defaultInstance(context))
            setTitle(context.txt(R.string.title_dark_mode))
            setAllowDrag(true)

            addItem(QMUIBottomSheetListItemModel(
                context.txt(R.string.dark_mode_default), null
            ).apply {
                skinImageSrcAttr(R.attr.app_skin_icon_dark_mode_off)
            })
            addItem(QMUIBottomSheetListItemModel(
                context.txt(R.string.dark_mode_force_dark), null
            ).apply {
                skinImageSrcAttr(R.attr.app_skin_icon_dark_mode_on)
            })
            addItem(QMUIBottomSheetListItemModel(
                context.txt(R.string.dark_mode_follow_system), null
            ).apply {
                skinImageSrcAttr(R.attr.app_skin_icon_dark_mode_auto)
            })

            setFitNav(true)

            addContentFooterView(confirmBinding.root)

            setOnSheetItemClickListener { dialog, _, position, _ ->
                confirmBinding.root.tag = position
                dialog.getBottomSheetListAdapter()?.setCheckedIndex(position)
            }
        }.build()

        confirmBinding.btnCancel.onThrottleClick {
            dialog.dismiss()
        }

        confirmBinding.btnSure.onThrottleClick {
            val mode = when ((confirmBinding.root.tag as? Int?) ?: 0) {
                1 -> SettingConstants.DarkModeForceDark
                2 -> SettingConstants.DarkModeFollowSystem
                else -> SettingConstants.DefaultDarkMode
            }
            onDarkModeSelected(dialog, mode)
        }

        return dialog
    }

    fun createFontSizeVBrowserDialog(
        context: Context, onProgressChanged: (Int) -> Unit = {}, fontSize: Int
    ) {
        val dialog = QMUIBaseDialog(context, R.style.MessageDialogStyle)
        dialog.setSkinManager(QMUISkinManager.defaultInstance(context))
        val contentBinding = LayoutMenuFontSizeBinding.inflate(LayoutInflater.from(context))
        dialog.setContentView(contentBinding.root)
        contentBinding.apply {
            btnFontDecrease.onThrottleClick {
                val currentProgress = fontSizeSeekBar.leftSeekBar.progress
                fontSizeSeekBar.setProgress(currentProgress - 20)
            }
            btnFontIncrease.onThrottleClick {
                val currentProgress = fontSizeSeekBar.leftSeekBar.progress
                fontSizeSeekBar.setProgress(currentProgress + 20)
            }
            fontSizeSeekBar.setOnRangeChangedListener(object : OnRangeChangedListener {
                override fun onRangeChanged(
                    view: RangeSeekBar?, leftValue: Float, rightValue: Float, isFromUser: Boolean
                ) {
                    val fontSize = leftValue.toInt()
                    if (fontSize in 80..160 step 20) {
                        onProgressChanged(leftValue.toInt())
                    }
                }

                override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {

                }

                override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {

                }
            })
            fontSizeSeekBar.setProgress(fontSize.toFloat())
        }

        dialog.apply {
            window?.also { window ->
                val lp = window.attributes
                lp.width = WindowManager.LayoutParams.MATCH_PARENT
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                lp.gravity = Gravity.BOTTOM
                window.setBackgroundDrawableResource(R.color.transparent)
                window.attributes = lp
            }
        }

        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
    }

    /**
     * 无图模式窗口
     */
    fun createImageModeDialog(
        context: Context, imageMode: Int, onImageModeSelected: (QMUIBottomSheet, Int) -> Unit
    ): QMUIBottomSheet {
        val checkIndex = if (imageMode == SettingConstants.ImageModeBlock) 1 else 0
        val confirmBinding = createConfirmFooterView(context)
        val dialog = BottomListSheetBuilder(context, true).apply {
            setCheckedIndex(checkIndex)
            setSkinManager(QMUISkinManager.defaultInstance(context))
            setTitle(context.txt(R.string.title_image_mode))
            setAllowDrag(true)

            addItem(context.str(R.string.image_mode_auto))
            addItem(context.str(R.string.image_mode_block))

            setFitNav(true)

            addContentFooterView(confirmBinding.root)

            setOnSheetItemClickListener { dialog, _, position, _ ->
                confirmBinding.root.tag = position
                dialog.getBottomSheetListAdapter()?.setCheckedIndex(position)
            }
        }.build()

        confirmBinding.btnCancel.onThrottleClick {
            dialog.dismiss()
        }

        confirmBinding.btnSure.onThrottleClick {
            val currentPosition = (confirmBinding.root.tag as? Int?) ?: 0
            val mode =
                if (currentPosition == 1) SettingConstants.ImageModeBlock else SettingConstants.ImageModeAuto
            onImageModeSelected(dialog, mode)
        }

        return dialog
    }

    fun createImageBlockCenterDialog(
        context: Context, imageMode: Int, onImageModeSelected: (Int) -> Unit
    ) {
        val dialog = QMUIBaseDialog(context, R.style.MessageDialogStyle)
        dialog.setSkinManager(QMUISkinManager.defaultInstance(context))
        val contentBinding = DialogImgBlockCenterBinding.inflate(LayoutInflater.from(context))
        dialog.setContentView(contentBinding.root)
        contentBinding.apply {
            if (imageMode == SettingConstants.ImageModeBlock) {
                ivImgBlock.visible()
                ivImgBlockAuto.gone()
            } else {
                ivImgBlock.gone()
                ivImgBlockAuto.visible()
            }
            llImgBlock.onThrottleClick {
                root.tag = 1
                ivImgBlock.visible()
                ivImgBlockAuto.gone()
            }
            llImgBlockAuto.onThrottleClick {
                root.tag = 0
                ivImgBlock.gone()
                ivImgBlockAuto.visible()
            }
            btnCancel.onThrottleClick {
                dialog.dismiss()
            }
            btnSure.onThrottleClick {
                val currentPosition = (root.tag as? Int?) ?: 0
                val mode =
                    if (currentPosition == 1) SettingConstants.ImageModeBlock else SettingConstants.ImageModeAuto
                onImageModeSelected(mode)
                dialog.dismiss()
            }
        }

        dialog.apply {
            window?.also { window ->
                val lp = window.attributes
                lp.width = WindowManager.LayoutParams.MATCH_PARENT
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                lp.gravity = Gravity.CENTER
                window.setBackgroundDrawableResource(R.color.transparent)
                window.attributes = lp
            }
        }

        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
    }

    fun createMenuDialog(
        context: Context,
        userClickListener: MenuBottomSheet.UserClickListener? = null,
        menuSettingClickListener: MenuBottomSheet.MenuSettingClickListener? = null,
        menuItemListener: MenuBottomSheet.MenuItemListener? = null,
        onPageSelected: (Int) -> Unit = {}
    ): MenuBottomSheet {
        return MenuBottomSheet.Builder(context).setUserClickListener(userClickListener)
            .setMenuSettingClickListener(menuSettingClickListener)
            .setMenuItemClickListener(menuItemListener).setPageSelectListener(onPageSelected)
            .setRowCount(2).setRadius(context.dip(24)).addNormalMenuItem(
                R.id.menu_id_favorites,
                R.string.menu_item_favorites,
                R.attr.app_skin_state_menu_icon_favorites
            )
//            .addNormalMenuItem(
//                R.id.menu_id_download,
//                R.string.menu_item_download,
//                R.attr.app_skin_state_menu_icon_download
//            )
            .addNormalMenuItem(
                R.id.menu_id_book, R.string.menu_item_book, R.attr.app_skin_state_menu_icon_book
            )
//            .addNormalMenuItem(
//                R.id.menu_id_video, R.string.menu_item_video, R.attr.app_skin_state_menu_icon_video
//            )
            .addToggleMenuItem(
                R.id.menu_id_collect,
                R.string.menu_item_collect,
                R.attr.app_skin_state_menu_icon_collect,
                textOnRes = R.string.menu_item_cancel_collect
            ).addNormalMenuItem(
                R.id.menu_id_dark_mode,
                R.string.menu_item_dark_mode,
                R.attr.app_skin_state_menu_icon_dark_mode
            )
            .addToggleMenuItem(
                R.id.menu_id_reader_mode,
                R.string.menu_item_reader_mode,
                R.attr.app_skin_state_menu_icon_reader
            )
            .addNormalMenuItem(
                R.id.menu_id_refresh,
                R.string.menu_item_refresh,
                R.attr.app_skin_state_menu_icon_refresh
            ).apply {
                addNormalMenuItem(
                    R.id.menu_id_exit, R.string.menu_item_exit, R.attr.app_skin_state_menu_icon_exit
                )
            }
//            .addNormalMenuItem(
//                R.id.menu_id_translate,
//                R.string.menu_item_translate,
//                R.attr.app_skin_state_menu_icon_translate
//            ).addToggleMenuItem(
//                R.id.menu_id_page_join,
//                R.string.menu_item_page_join,
//                R.attr.app_skin_state_menu_icon_page_join
//            )
            .addNormalMenuItem(
                R.id.menu_id_no_image,
                R.string.menu_item_no_image,
                R.attr.app_skin_state_menu_icon_no_image_mode
            )
//            .addToggleMenuItem(
//                R.id.menu_id_fullscreen,
//                R.string.menu_item_fullscreen,
//                R.attr.app_skin_state_menu_icon_fullscreen
//            )
            .addToggleMenuItem(
                R.id.menu_id_privacy_mode,
                R.string.menu_item_privacy_mode,
                R.attr.app_skin_state_menu_icon_privacy_mode
            ).addToggleMenuItem(
                R.id.menu_id_lock_portrait,
                R.string.menu_item_lock_portrait,
                R.attr.app_skin_state_menu_icon_lock_portrait
            ).addNormalMenuItem(
                R.id.menu_id_clear_cache,
                R.string.menu_item_clear_cache,
                R.attr.app_skin_state_menu_icon_clear_cache
            ).addNormalMenuItem(
                R.id.menu_id_ua_setting, R.string.menu_item_ua, R.attr.app_skin_state_menu_icon_ua
            )
//            .addNormalMenuItem(
//                R.id.menu_id_page_find,
//                R.string.menu_item_page_find,
//                R.attr.app_skin_state_menu_icon_find
//            ).addNormalMenuItem(
//                R.id.menu_id_color_pick,
//                R.string.menu_item_color_pick,
//                R.attr.app_skin_state_menu_icon_color_pick
//            )
            .addNormalMenuItem(
                R.id.menu_id_font, R.string.menu_item_font, R.attr.app_skin_state_menu_icon_font
            )
//            .addNormalMenuItem(
//                R.id.menu_id_screenshot,
//                R.string.menu_item_screenshot,
//                R.attr.app_skin_state_menu_icon_screenshot
//            )
//            .addNormalMenuItem(
//                R.id.menu_id_save_page,
//                R.string.menu_item_save_page,
//                R.attr.app_skin_state_menu_icon_save_page
//            )
//            .addNormalMenuItem(
//                R.id.menu_id_report, R.string.menu_item_report, R.attr.app_skin_state_menu_icon_report
//            )
            .addNormalMenuItem(
                R.id.menu_id_windows,
                R.string.menu_item_windows,
                R.attr.app_skin_state_menu_icon_windows
            ).build()

    }

}